﻿// This file is part of GEOTRON.

// GEOTRON is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The GEOTRON library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with GEOTRON.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Geotron
{
    /// <summary>
    /// Includes functions for calculating distance.
    /// </summary>
    public static partial class Library
    {
        /// <summary>
        /// Calculates the distance between the specified co-ordinates.
        /// </summary>
        /// <param name="Input1">The first location.</param>
        /// <param name="Input2">The second location.</param>
        /// <returns>The distance between them in meters.</returns>
        /// <remarks>Appears to be about right, but hasn't been tested.</remarks>
        public static double HaversineDistance(Location Input1, Location Input2)
        {
            double r = 6367.45 * Math.Pow(10, 3);

            Input1.Mode = AngleType.Radians;
            Input2.Mode = AngleType.Radians;

            double dLat = Input2.Latitude - Input1.Latitude;
            double dLon = Input2.Longitude - Input1.Longitude;

            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(Input1.Latitude) + Math.Cos(Input2.Latitude) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
            return r * c;
        }
    }
}
